import {
  Http
} from "../../utils/http"
import {
  Order
} from "../../model/Order"
import {
  Pay
} from "../../model/Pay"
import {
  Wallet
} from '../../model/wallet'

const app = getApp();
Page({

  data: {
    shop_name: "请选择店铺名 (必选项)",
    shop_location: "",
    store_id: "",
    order_no: "",
    resList: [],
    username: '',
    phone: '',
    distributor_id: "", //通过扫码进来的  店铺取当前值 
    show: false,
    placeMoney: 5.2, //商品价格
    showacny: false,
    pwd: '',
    money: 0,
    currentValue: '', //提交密码
    tabs: [], //得到选中的商品数组
    prodID: '',
    address: '', //店铺地址
    product_right_ids: ''
  },

  //生命周期函数--监听页面加载
  onLoad: function (options) {
    this.setData({
      phone: wx.getStorageSync("phone"),
      tabs: wx.getStorageSync('tabs'),

      shop_name: options.store_name,
      distributor_id: options.distributor_id,
      store_id: options.store_id,
      phone: options.phone,
      username: options.username,
      show: options.show,

      product_right_ids: wx.getStorageSync('product_right_ids'),
      product_id: wx.getStorageSync('prodID'),
      placeMoney: wx.getStorageSync('placeMoney'),
      address: options.address
    })
    if (Object.prototype.toString.call(options.mack) === '[object Undefined]') {
      this.ongetShop();
    }

  },

  //获取金额的自定义函数
  money(wallet) {
    if (wallet.code == 0) {
      this.setData({
        balance_icon: wallet.data.balance_icon,
        money: wallet.data.balance
      })
    } else {
      wx.showToast(wallet.msg)
    }
  },

  //生命周期函数--监听页面显示
  onShow: async function () {
    let a = await Http.login()
    let wallet = await Wallet.get_user_balance()
    //执行 获取金额的自定义函数
    this.money(wallet);
  },

  //分销进来后得到分销员所在店铺并且展示
  ongetShop: function () {
    let that = this;
    let att = wx.getStorageSync('shoplist'); //赋值 店铺名列表
    let scene = wx.getStorageSync('scene'); //赋值 场景值
    let arr = scene.split(",");
    for (let index = 0; index < att.length; index++) {
      if (att[index].id == parseInt(arr[2])) {
        that.setData({
          shop_name: att[index].name,
          store_id: att[index].id
        })
      }
    }

  },

  touchStartTj(e) {
    this.touchStartTime = e.timeStamp; //赋值开始的时间
  },
  touchEndTj(e) {
    this.touchEndTime = e.timeStamp; //赋值结束的时间
  },
  //点击提交订单
  orderPay: async function (e) {
    // 控制点击事件在350ms内触发，加这层判断是为了防止长按时会触发点击事件
    if (this.touchEndTime - this.touchStartTime < 350) {
      var currentTime = e.timeStamp; // 当前点击的时间
      var lastTapTime = this.lastTapTime; //最后一次点击时间
      this.lastTapTime = currentTime; // 更新最后一次点击时间
      // 如果两次点击时间在500ms内，则认为是双击事件
      if (currentTime - lastTapTime > 1000 || lastTapTime == undefined) {
        if (this.data.product_right_ids != '') { //判断是否是权益卡 !=''是权益卡，==''反之

          if (this.data.distributor_id != "" && this.data.distributor_id != undefined) {
            if (!(/^[\u4E00-\u9FA5A-Za-z]+$/.test(this.data.username))) {
              wx.showToast({
                title: '姓名有误',
                duration: 2000,
                icon: 'none'
              });
            } else if (!(/^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}$/.test(this.data.phone))) {
              wx.showToast({
                title: '手机号码有误',
                duration: 2000,
                icon: 'none'
              });
            } else if (this.data.placeMoney == 0 || this.data.placeMoney == '00.00') {
              this.onPlaceOrderBalanceProduct()
              this.walletPay();
            } else {
              this.onPlaceOrderBalanceProduct();
            }
          } else {
            if (!(/^[\u4E00-\u9FA5A-Za-z]+$/.test(this.data.username))) {
              wx.showToast({
                title: '姓名有误',
                duration: 2000,
                icon: 'none'
              });
            } else if (!(/^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}$/.test(this.data.phone))) {
              wx.showToast({
                title: '手机号码有误',
                duration: 2000,
                icon: 'none'
              });
            } else if (this.data.placeMoney == 0 || this.data.placeMoney == '00.00') {
              this.onPlaceOrderBalanceProduct();
              this.walletPay();
            } else {
              this.onPlaceOrderBalanceProduct();
            }

          }

        } else {
          if (this.data.distributor_id != "" && this.data.distributor_id != undefined) {
            if (!(/^[\u4E00-\u9FA5A-Za-z]+$/.test(this.data.username))) {
              wx.showToast({
                title: '姓名有误',
                duration: 2000,
                icon: 'none'
              });
            } else if (!(/^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}$/.test(this.data.phone))) {
              wx.showToast({
                title: '手机号码有误',
                duration: 2000,
                icon: 'none'
              });
            } else if (this.data.placeMoney == 0 || this.data.placeMoney == '00.00') {
              this.onPlaceOrderBalanceProduct()
              this.walletPay();
            } else {

              this.onPlaceOrderBalanceProduct();

            }
          } else {
            if (this.data.store_id == null || this.data.store_id == "") {
              wx.showModal({
                title: '提示',
                content: "选择门店"
              })
            } else if (!(/^[\u4E00-\u9FA5A-Za-z]+$/.test(this.data.username))) {
              wx.showToast({
                title: '姓名有误',
                duration: 2000,
                icon: 'none'
              });
            } else if (!(/^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}$/.test(this.data.phone))) {
              wx.showToast({
                title: '手机号码有误',
                duration: 2000,
                icon: 'none'
              });
            } else if (this.data.placeMoney == 0 || this.data.placeMoney == '00.00') {
              this.onPlaceOrderBalanceProduct();
              this.walletPay();
            } else {

              this.onPlaceOrderBalanceProduct();

            }

          }
        }

      } else {
        //模拟网络请求
        wx.showToast({
          title: '请勿多次点击',
          icon: 'error'
        })
        await setTimeout(function () {
          wx.hideToast()
        }, 2000)
      }
    }
  },

  touchStartMf(e) {
    this.touchStartTime = e.timeStamp; //赋值开始的时间
  },
  touchEndMf(e) {
    this.touchEndTime = e.timeStamp; //赋值结束的时间
  },
  //点击免费领取
  orderPayMf: async function (e) {
    // 控制点击事件在350ms内触发，加这层判断是为了防止长按时会触发点击事件
    if (this.touchEndTime - this.touchStartTime < 350) {
      var currentTime = e.timeStamp; // 当前点击的时间
      var lastTapTime = this.lastTapTime; //最后一次点击时间
      this.lastTapTime = currentTime; // 更新最后一次点击时间

      // 如果两次点击时间在500ms内，则认为是双击事件
      if (currentTime - lastTapTime > 1000 || lastTapTime == undefined) {

        if (this.data.product_right_ids != '') {
          if (this.data.distributor_id != "" && this.data.distributor_id != undefined) {
            if (!(/^[\u4E00-\u9FA5A-Za-z]+$/.test(this.data.username))) {
              wx.showToast({
                title: '姓名有误',
                duration: 2000,
                icon: 'none'
              });
            } else if (!(/^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}$/.test(this.data.phone))) {
              wx.showToast({
                title: '手机号码有误',
                duration: 2000,
                icon: 'none'
              });
            } else {
              //领取免费商品
              let order = await Order.get_token_order(this.data.tabs.id, parseInt(this.data.store_id), this.data.username, this.data.phone);
              console.log(order.msg);
              console.log(order);
              if (order.code == 0) {
                wx.redirectTo({
                  url: '/pages/ordercenter/index',
                })
              } else {
                console.log(order.msg);
              }
            }
          } else {
            if (!(/^[\u4E00-\u9FA5A-Za-z]+$/.test(this.data.username))) {
              wx.showToast({
                title: '姓名有误',
                duration: 2000,
                icon: 'none'
              });
            } else if (!(/^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}$/.test(this.data.phone))) {
              wx.showToast({
                title: '手机号码有误',
                duration: 2000,
                icon: 'none'
              });
            } else {
              //领取免费商品
              let order = await Order.get_token_order(this.data.tabs.id, parseInt(this.data.store_id), this.data.username, this.data.phone);
              console.log(order.msg);
              console.log(order);
              if (order.code == 0) {
                wx.redirectTo({
                  url: '/pages/ordercenter/index',
                })
              } else {
                console.log(order.msg);
              }
            }
          }
        }

      } else {
        //模拟网络请求
        wx.showToast({
          title: '请勿多次点击',
          icon: 'error'
        })
        await setTimeout(function () {
          wx.hideToast()
        }, 2000)
      }
    }
  },

  //页面初次渲染
  onReady: function () {
    //判断this.daat.phone 是否为 空
    if (this.data.phone == "" || this.data.phone == null) {
      this.setData({
        username: app.globalData.username,
        phone: app.globalData.phone
      })
    } else {
      this.setData({
        username: app.globalData.username
      })
    }

  },

  //关闭钱包支付和微信支付
  onClose() {
    this.setData({
      show: false
    });
  },

  // 点击钱包支付 输入支付密码 设置支付密码
  walletPay: function () {
    let that = this;
    if (wx.getStorageSync('payment_password') == 1) {
      if (this.data.placeMoney == 0 || this.data.placeMoney == '00.00') {
        that.setData({
          showacny: true,
          show: false
        });
      } else if (parseFloat(this.data.money) > parseFloat(this.data.placeMoney)) {
        that.setData({
          showacny: true,
          show: false
        });
      } else {
        wx.showModal({
          title: '提示',
          content: '您的余额：￥' + this.data.money + '\r\n商品价格：￥' +
            this.data.placeMoney +
            '\r\n余额不足请充值后再试',
          success(res) {
            if (res.confirm) {

            } else if (res.cancel) {}
          }
        })
      }
    } else {
      wx.showModal({
        title: '提示',
        content: '亲！你还未设置支付密码,是否现在设置',
        success(res) {
          if (res.confirm) {
            // store_id phone username {{this.data.store_id}}&phone={{this.data.phone}}&username={{this.data.username}}
            wx.navigateTo({
              url: '/pages/pad/index?store_id=' + that.data.store_id + '&phone=' + that.data.phone + '&username=' + that.data.username + '&mack=1'
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  },


  //获取余额支付-下单
  onPlaceOrderBalanceProduct: async function () {
    //获取余额支付-下单
    let result = await Order.get_place_order(this.data.product_id, this.data.store_id, this.data.username, this.data.phone);
    console.log(result.msg);
    if (result.code == 0) {
      // 弹出钱包支付和微信支付
      this.setData({
        show: true
      })
      this.setData({
        order_no: result.data.order_no
      })
    } else if (result.msg == '已经参加过该活动了, 不能再参加了') {
      wx.showModal({
        title: "提示",
        content: result.msg,
        showCancel: false,
        success(res) {
          if (res.confirm) {
            wx.navigateBack()
          }
        }
      })
    } else {
      console.log(result);
    }
  },

  //余额支付-支付
  onPayBalanceProduct: async function (order_no) {
    let result = await Pay.get_pay_balance_product(order_no, this.data.currentValue);
    console.log(result.msg);
    if (result.code == 0) {
      wx.redirectTo({
        url: "/pages/paymoney/index?money=" + this.data.placeMoney
      })
    } else {
      this.passwordBox = this.selectComponent('#passwordBox');
      this.passwordBox.clearCurrentValue();
      console.log(result);
      wx.showToast({
        title: result.msg,
        duration: 2000,
        icon: 'none'
      });
    }
  },

  touchStartWx(e) {
    this.touchStartTime = e.timeStamp; //赋值开始的时间
  },
  //微信支付点击结束的时间
  touchEndWx(e) {
    this.touchEndTime = e.timeStamp; //赋值结束的时间
  },
  //微信支付
  onpay: async function (e) {
    // 控制点击事件在350ms内触发，加这层判断是为了防止长按时会触发点击事件
    if (this.touchEndTime - this.touchStartTime < 350) {
      var currentTime = e.timeStamp; // 当前点击的时间26
      var lastTapTime = this.lastTapTime; //最后一次点击时间24
      this.lastTapTime = currentTime; // 更新最后一次点击时间12
     
      // 如果两次点击时间在500ms内，则认为是双击事件
      if (currentTime - lastTapTime > 1000 || lastTapTime == undefined) {
        console.log("调起wx支付");
        
        //获取 微信统一支付接口
        let result = await Pay.get_pay(this.data.order_no);
        if (result.code == 0) {
          wx.requestPayment({
            timeStamp: result.data.timeStamp,
            nonceStr: result.data.nonceStr,
            package: result.data.package,
            signType: result.data.signType,
            paySign: result.data.paySign,
            success(res) {
              wx.redirectTo({
                url: "/pages/share/index"
              })
            }
          })
        } else {
          wx.showToast({
            title: '提示',
            content: "result.msg"
          })
        }



      } else {
        //模拟网络请求
        wx.showToast({
          title: '请勿多次点击',
          icon: 'error'
        })
        await setTimeout(function () {
          wx.hideToast()
        }, 2000)
      }
    }

  },

  //关闭钱包支付
  onCloses() {
    this.setData({
      showacny: false
    });
  },

  //监听input框
  inputChange(e) {
    this.passwordBox = this.selectComponent('#passwordBox') //清空
    let currentValue = e.detail
    this.setData({
      currentValue
    })
    if (currentValue.length == 6) {
      console.log(this.data.currentValue);
      this.onPayBalanceProduct(this.data.order_no);
      this.setData({
        showacny: false
      });
      this.passwordBox.clearCurrentValue();
    }
  }

})